package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dto.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.common.MD5Utils;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper , ApUser> implements ApUserService{

    @Autowired
    private ApUserMapper apUserMapper;

    @Override
    public ResponseResult login(LoginDto loginDto) {
        //1.判断登录用户还是游客登录
        Long id = 0L;
        ApUser apUser = null;
        if (loginDto != null && !StringUtils.isEmpty(loginDto.getPhone()) && !StringUtils.isEmpty(loginDto.getPassword())){
            //2.用户登录,校验
            LambdaQueryWrapper<ApUser> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ApUser::getPhone,loginDto.getPhone());
            //3. 根据用户输入手机号查询用户 , 获取用户密码与盐
            apUser = apUserMapper.selectOne(wrapper);
            //4.前台传递密码加盐后使用MD5加密后与用户密码校验
            String pwd = MD5Utils.encodeWithSalt(loginDto.getPassword(), apUser.getSalt());
            if (pwd.equals(apUser.getPassword())){
                id = apUser.getId().longValue();
                apUser.setPassword("*");
            }else {
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR , AppHttpCodeEnum.LOGIN_PASSWORD_ERROR.getErrorMessage());
            }
        }
        //5.根据用户id创建token令牌
        //6.如果是游客登录 , 根据0创建token令牌
        String token = AppJwtUtil.getToken(id);
        Map<String, Object> map = new HashMap<>();
        map.put("token" , token);
        if (apUser != null){
            map.put("user" , apUser);
        }
        return ResponseResult.okResult(map);
    }

    public static void main(String[] args) {
        System.out.println(MD5Utils.encodeWithSalt("admin" ,"hhh") );
    }
}
